package org.cy.algorithm.chapter_02;

import org.cy.algorithm.util.AlgorithmUtil;

/**
 * 书中2-4原题，使用归并排序，求逆序对个数
 */
public class ReversePair_2_4 {

    private int reversePairCount(int[] nums) {
        if (nums == null || nums.length <= 1) {
            return 0;
        }

        return reversePairCount(nums, 0, nums.length - 1);
    }

    private int reversePairCount(int[] nums, int left, int right) {
        if (left >= right) {
            return 0;
        }

        int mid = left + (right - left) / 2;
        int leftReversePairCount = reversePairCount(nums, left, mid);
        int rightReversePairCount = reversePairCount(nums, mid + 1, nums.length - 1);
        int mergedPairCount = mergeReversePair(nums, left, mid, right);

        return leftReversePairCount + rightReversePairCount + mergedPairCount;
    }

    private int mergeReversePair(int[] nums, int left, int mid, int right) {
        int result = 0;
        int[] temp = new int[right - left + 1];

        int p1 = left;
        int p2 = mid + 1;
        int i = 0;
        while (p1 <= mid && p2 <= right) {
            if (nums[p1] > nums[p2]) {
                result += mid - p1 + 1;
                temp[i++] = nums[p2++];
            } else {
                temp[i++] = nums[p1++];
            }
        }
        while (p1 <= mid) {
            temp[i++] = nums[p1++];
        }
        while (p2 <= right) {
            temp[i++] = nums[p2++];
        }

        for (i = 0; i < temp.length; i++) {
            nums[left++] = temp[i];
        }
        return result;
    }

    public static int violent(int[] nums) {
        int reversePairCount = 0;
        for (int i = 0; i < nums.length; i++) {
            for (int j = i + 1; j < nums.length; j++) {
                if (nums[i] > nums[j]) {
                    reversePairCount++;
                }
            }
        }
        return reversePairCount;
    }

    public static void main(String[] args) {
        for (int i = 0; i < 1000; i++) {
            int[] nums = AlgorithmUtil.createRandomArray(20);
            ReversePair_2_4 pair = new ReversePair_2_4();
            if (violent(AlgorithmUtil.copyArray(nums)) !=
                    pair.reversePairCount(AlgorithmUtil.copyArray(nums))) {
                System.out.println("Oops");
                return;
            }
        }
        System.out.printf("OK");
    }
}
